<?php

class AdminSettingsController extends BaseClass {
	
	public $title;
	public $layout = 'main';
	
	public function actions() {
	
	}
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError() {
		if($error = Yii::app()->errorHandler->error) {
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
				array('allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions' => array('index'),
						'users' => $this->getAdmins(),
				),
				array('deny', // deny other user to perform actions
						'actions' => array('index'),
						'users' => array('*'),
				),
		);
	}
	/*
	 * Function to change password of admin
	 */
	public function actionIndex() {
		$this->title = Yii::app()->name.' :: Admin-Setting';
		$model = $this->_loadModel(Yii::app()->user->getState('userId'));
		if(isset($_POST['submit'])) {
			if($_POST['new_password'] === $_POST['conf_password'] ) {
				if(md5($_POST['old_password']) == $model->password) {
					 if(1 == Yii::app()->user->getState('isAdmin')) {
					 	$model->password = md5($_POST['new_password']);
					 	if($model->save()) {
					 		Yii::app()->user->setFlash('success', 'Password has been changed successfully!');
					 	}
					 }
				}
				else {
					Yii::app()->user->setFlash('error', 'Old Password is not correct!');
				}
			}
			else {
				Yii::app()->user->setFlash('error', 'Password and Confirm Password field do not match!');
			}
		}
		$this->render('index', array('model' => $model));
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
protected function _loadModel($id) {

        $model = Users::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }
}